package com.ns.attendance.task;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import com.ns.attendance.core.CheckAttendance;
import com.ns.attendance.dao.model.MonthlyFlag;
import com.ns.attendance.dao.model.Users;
import com.ns.attendance.service.MonthlyFlagService;
import com.ns.attendance.service.UsersService;
import com.ns.attendance.util.DaysUtil;

/**
 * @author Han
 */
@Component
public class NoticeTask {
	private static final Logger log = LoggerFactory.getLogger(NoticeTask.class);
	@Autowired
	private MonthlyFlagService monthService;
	
	@Autowired
	private UsersService userService;
	
	@Autowired
	private ThreadPoolTaskExecutor executor;
	
	@Scheduled(cron = "0 30 8 * * ?")
	public void work() {
		log.info("任务开始...");
		//非工作日不执行,直到周一再开始检查周五的
		Calendar ca = Calendar.getInstance();
		if(!DaysUtil.isWorkDay(ca)){
			return;
		}
		
		Date date = new Date();
		String monthid = new SimpleDateFormat("yyyyMM").format(date);
		MonthlyFlag monthly = monthService.get(monthid);
		boolean flag = false;
		if(monthly == null){
			log.info("当前是月初，将发送月份汇总...");
			flag = true;
			monthly = new MonthlyFlag();
			monthly.setIndex(monthid);
			monthService.save(monthly);
		}
		final boolean checkmonth = flag;
		List<Users> users = userService.findAll();
		
		try {
			CheckAttendance.initClient();
		} catch (Exception e) {
			return;
		}
		for(final Users user : users){
			executor.execute(new Runnable() {
				@Override
				public void run() {
					CheckAttendance.notice(user, checkmonth);
				}
			});
		}
	}
}
